package com.zlsy.thread.service.impl;

import com.zlsy.thread.dto.SynchDTO;
import com.zlsy.thread.service.SynchronizedTestService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author zhouliang
 * @date 2020/03/02
 **/
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SynchronizedTestServiceImpl implements SynchronizedTestService {

    final Object lock = new Object();

    @Override
    public void query(SynchDTO synchDTO) {
       /* //对象锁为当前实例：线程安全吗？ 测试结果来看是安全的；
        synchronized (this) {
            String result = getQuery();
            System.err.println(result);
        }*/

        System.err.println(this.lock);
        synchronized (lock) {
            String result = getQuery();
            System.err.println(result);
        }

        //有一直种情况会导致线程不安全的情况 加了 spring aop的事务申明标签，会在方法前开启事务，方法结束提交事务
        // synchronized 锁的范围不再这个里面，提交事务的时候 如果不控制（乐观锁等）会导致并发安全
    }

    private static String getQuery() {
        log.info("当前线程叫:{}", Thread.currentThread().getName());
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info(Thread.currentThread().getName() + "：我运行完了");
        return String.valueOf(Math.random());
    }
/*
    private static synchronized String getQuery() {
        log.info("当前线程叫:{}", Thread.currentThread().getName());
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info(Thread.currentThread().getName() + "：我运行完了");
        return String.valueOf(Math.random());
    }
*/
}
